package edu.neusoft.yuejian_09.activity;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.util.List;

import edu.neusoft.yuejian_09.R;
import edu.neusoft.yuejian_09.adapter.TrainSearchAdapter;
import edu.neusoft.yuejian_09.base.RetrofitListener;
import edu.neusoft.yuejian_09.bean.Train;
import edu.neusoft.yuejian_09.model.TrainModel;

public class TrainSearchActivity extends Activity implements RetrofitListener<List<Train>> {

    private RecyclerView recyclerView;
    private EditText et_search;
    private Button btn_search;
    private String search_key;
    private ImageView img_return;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_train_search);
        initViews();
        initEvents();

    }

    private  void initViews(){
        et_search = (EditText)findViewById(R.id.search_input);
        btn_search = (Button)findViewById(R.id.search_btn);
        img_return= (ImageView) findViewById(R.id.img_return);
        recyclerView = (RecyclerView)findViewById(R.id.rv_trainsearch);
    }

    private void initEvents(){
        img_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                search_key = et_search.getText().toString();
                getData();
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    public void getData() {
        TrainModel trainModel= new TrainModel();
        trainModel.getTrainBySearch(search_key,this);

    }

    @Override
    public void onSuccess(final List<Train> data,int flag ){

        System.out.printf("data");
        if ((data.size())==0){
            Toast.makeText(TrainSearchActivity.this,"没有搜到任何训练！",Toast.LENGTH_SHORT).show();
        }else{
            TrainSearchAdapter trainSearchAdapter=new TrainSearchAdapter(TrainSearchActivity.this,data);

            recyclerView.setAdapter(trainSearchAdapter);

        }

    }

    @Override
    public void onFail(){ Toast.makeText(TrainSearchActivity.this, "网络发生错误", Toast.LENGTH_SHORT).show();}

}
